package utils

import (
	"bytes"
	"encoding/base64"
	"github.com/disintegration/imaging"
	"github.com/nfnt/resize"
	"image"
	"image/jpeg"
	"image/png"
)

// 图片处理工具类
type ImageUtils struct{}

// Base64 转图片
func (i *ImageUtils) Base64ToImage(base64Str string) (image.Image, error) {
	// 解码 base64
	data, err := base64.StdEncoding.DecodeString(base64Str)
	if err != nil {
		return nil, err
	}

	// 解码图片
	img, _, err := image.Decode(bytes.NewReader(data))
	if err != nil {
		return nil, err
	}

	return img, nil
}

// 图片转 Base64
func (i *ImageUtils) ImageToBase64(img image.Image, format string) (string, error) {
	buf := new(bytes.Buffer)

	// 根据格式编码图片
	switch format {
	case "png":
		err := png.Encode(buf, img)
		if err != nil {
			return "", err
		}
	case "jpg", "jpeg":
		err := jpeg.Encode(buf, img, &jpeg.Options{Quality: 75})
		if err != nil {
			return "", err
		}
	default:
		err := png.Encode(buf, img)
		if err != nil {
			return "", err
		}
	}

	// 转换为 base64
	return base64.StdEncoding.EncodeToString(buf.Bytes()), nil
}

// 调整图片大小
func (i *ImageUtils) ResizeImage(img image.Image, width, height uint) image.Image {
	return resize.Resize(width, height, img, resize.Lanczos3)
}

// 裁剪图片
func (i *ImageUtils) CropImage(img image.Image, x, y, width, height int) image.Image {
	return imaging.Crop(img, image.Rect(x, y, x+width, y+height))
} 